package my2Cents.tools;

import java.awt.event.MouseEvent;

import my2Cents.Sandbox;
import my2Cents.Undo;
import my2Cents.Util;
import net.phys2d.math.Vector2f;
import net.phys2d.raw.Body;
import net.phys2d.raw.StaticBody;
import net.phys2d.raw.shapes.PBox;
import net.phys2d.raw.shapes.PLine;

public class MotorTool extends AbstractConstraintMaker {
	private Body body;
	
	public MotorTool() {
		setGhostColor(AbstractPhysTool.GHOSTCOLOR_MOVE);
		setName("Motor");
		thinkLevel = THINKLEVEL_MAX;
		setDescription(
				"Click on an object and drag to\n" +
				"add a motor and set it's speed"
			);
		removeProperty(2);
		removeProperty(2);
		removeProperty(2);
		removeProperty(2);
	}
	
	public void startTool(MouseEvent arg0) {
		super.startTool(arg0);
		body = Util.selectBody(arg0.getX(), arg0.getY(), getWorld());
		Util.clearHandle(getWorld());
		// || body instanceof StaticBody
		if(body == null) {
			endTool(arg0);
			return;
		} else {
			body.doOutlineFx();
		}
	}
	
	public void toolThink(MouseEvent arg0) {
		if(body != null) {
			end.x = arg0.getX();
			Vector2f bpos = (Vector2f) body.getPosition();
			end.y = start.y;
			//start.y = bpos.y;
			//start.x = bpos.x;
		}
	}
	
	public void endTool(MouseEvent arg0) {
		float x1 = start.x;
		float y1 = start.y;
		double angle = Util.angleVec(start,end);
		float distance = start.distance(end);
		float cx = (float) (Math.cos(angle)*distance/2);
		float cy = (float) (Math.sin(angle)*distance/2);
		
		if(body != null) {
			final Body myBod = body;
//			Sandbox.getUndoList().undo(body, "Motor");
//			Undo motorUndo = new Undo(body, getWorld(), "Motor") {
//				/**
//				 * 
//				 */
//				private static final long serialVersionUID = 3603895432586567091L;
//
//				public void performUndo() {
//					Body b = myBod;
//					b.setMotorSpeed(0);
//					b.doOutlineFx();
//				}
//			};
//			Sandbox.getUndoList().add(motorUndo);
		
			if(cx < 0) {
				body.setMotorSpeed(-distance/80);
			} else {
				body.setMotorSpeed(distance/80);
			}
		}

		inUse = false;
		sandbox.onToolEnd();
	}

}
